package controller.business.annualAssess;

import base.response.OffsetLimitPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import controller.common.BaseController;
import controller.common.StaticConstant;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import properties.SystemProperty;
import response.CommonResult;
import services.business.BusinessInfoServices;
import services.business.InspectorAssessServices;
import services.business.InspectorInfoServices;
import services.dictionary.ItemTypeServices;
import services.expertInfo.ExpertCertificateServices;
import services.specific.AnnualAssessServices;
import util.DateUtil;
import util.io.PoiExcelCreateUtil;
import wt.entity.expertInfo.ExpertCertificate;
import wt.entity.specific.AnnualAssess;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 功能:
 * 作者: 洪世成
 * 日期: 2017/9/9
 * 版权所有: admin
 */
@Controller
@RequestMapping("business/annualAssess")
public class AnnualAssessController extends BaseController {
    @Autowired
    AnnualAssessServices annualAssessServices;
    @Autowired
    BusinessInfoServices businessInfoServices;
    @Autowired
    InspectorInfoServices inspectorInfoServices;
    @Autowired
    InspectorAssessServices inspectorAssessServices;
    @Autowired
    ExpertCertificateServices expertCertificateServices;
    @Autowired
    ItemTypeServices itemTypeServices;


    @RequiresPermissions("business:annualAssess:default")
    @RequestMapping("index")
    public String index(Map map) throws Exception {
        map.put("itemTypeList", itemTypeServices.selectLiveItemType());
        return "business/annualAssess/index";
    }

    @RequestMapping(value = {"editDlg"})
    public String editDlg(String certificateId, String expertName, Map map) throws Exception {


        ExpertCertificate expertCertificate = expertCertificateServices.selectByPrimaryKey(certificateId);

        map.put("expertCertificate", expertCertificate);
        map.put("expertName", expertName);
        map.put(StaticConstant.EDIT_URL, "business/annualAssess/update");
        map.put(StaticConstant.EDIT_OPERATE_TYPE, StaticConstant.EDIT_UPDATE);
        return "business/annualAssess/editDlg";

    }

    @ResponseBody
    @RequestMapping(value = {"update"})
    public CommonResult update(String id, String grade) throws Exception {
        CommonResult result = new CommonResult();
        ExpertCertificate expertCertificate = new ExpertCertificate();
        expertCertificate.setId(id);
        expertCertificate.setGrade(grade);
        expertCertificateServices.adminUpdateByPrimaryKeySelective(expertCertificate);
        return result.setSuccess();
    }


    @RequiresPermissions("business:annualAssess:default")
    @ResponseBody
    @RequestMapping("select")
    public OffsetLimitPage select(
            String expertName,
            String itemId,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            String affiliate,
            Integer offset,
            Integer limit
    ) throws Exception {
        if (endTime != null) {
            endTime = DateUtil.moveDate(endTime, 1);
        }
        String itemTypeOverdueId;
        if ("369000000000004167".equals(itemId)) {//工许
            itemTypeOverdueId = SystemProperty.getIndustryOverdueId();
        } else if ("369000000000004171".equals(itemId)) {//检验检测
            itemTypeOverdueId = SystemProperty.getExamineOverdueId();
        } else {
            itemTypeOverdueId = "";
        }

        PageHelper.offsetPage(offset, limit);
        List<AnnualAssess> annualAssessList = annualAssessServices.select(expertName, itemId, itemTypeOverdueId, startTime, endTime, affiliate);
        processResults(annualAssessList);
        return new OffsetLimitPage((Page) annualAssessList);

    }

    @RequiresPermissions("business:annualAssess:default")
    @ResponseBody
    @RequestMapping("downLoadExcel")
    public void downLoadExcel(
            String expertName,
            String itemId,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            String affiliate,
            HttpServletResponse response
    ) throws Exception {
        if (endTime != null) {
            endTime = DateUtil.moveDate(endTime, 1);
        }
        String itemTypeOverdueId;
        if ("369000000000004167".equals(itemId)) {//工许
            itemTypeOverdueId = SystemProperty.getIndustryOverdueId();
        } else if ("369000000000004171".equals(itemId)) {//检验检测
            itemTypeOverdueId = SystemProperty.getExamineOverdueId();
        } else {
            itemTypeOverdueId = "";
        }


        List<AnnualAssess> annualAssessList = annualAssessServices.select(expertName, itemId, itemTypeOverdueId, startTime, endTime, affiliate);
        processResults(annualAssessList);

        List<Map> mapList = new ArrayList<Map>();
        for (AnnualAssess annualAssess : annualAssessList) {
            Map map = new HashMap();
            map.put("id", annualAssess.getId());
            map.put("name", annualAssess.getName());
            map.put("idCard", annualAssess.getIdCard());
            map.put("phone", annualAssess.getPhone());
            map.put("affiliate", annualAssess.getAffiliate());
            map.put("certificateId", annualAssess.getCertificateId());
            map.put("certificateNum", annualAssess.getCertificateNum());
            map.put("leaderCount", annualAssess.getLeaderCount());
            map.put("crewCount", annualAssess.getCrewCount());
            map.put("goodCount", annualAssess.getGoodCount());
            map.put("middleCount", annualAssess.getMiddleCount());
            map.put("badCount", annualAssess.getBadCount());
            map.put("reportCount", annualAssess.getReportCount());
            map.put("disciplineCount", annualAssess.getDisciplineCount());
            map.put("overtimeCount", annualAssess.getOvertimeCount());
            map.put("trainCount", annualAssess.getTrainCount());
            map.put("illegalCount", annualAssess.getIllegalCount());
            map.put("totalScore", annualAssess.getTotalScore());
            map.put("result", annualAssess.getResult());
            mapList.add(map);
        }

        PoiExcelCreateUtil poi = new PoiExcelCreateUtil(17);
        CellStyle headStyle = poi.createCellStyle(poi.FONT_HEIGHT_DEFAULT, poi.FONT_WEIGHT_BOLE, poi.FONT_NAME_SONG, null);
        CellStyle bodyStyle = poi.createCellStyle(poi.FONT_HEIGHT_DEFAULT, poi.FONT_WEIGHT_NORMAL, poi.FONT_NAME_SONG, null);

        poi.createSheet("sheet1",
                null,
                new String[]{"姓名", "身份证号", "证书编号", "所属单位", "担任组长次数", "担任组员次数", "现场审查工作评价（ 好 ）", "现场审查工作评价（一般）", "现场审查工作评价（ 差 ）",
                        "观察报告存在问题次数", "纪律反馈存在问题次数", "上报材料超期次数", "无故缺勤次数", "投诉检举情况", "年度评定分数", "年度评定结果", "升降级"},
                new String[]{"name", "idCard", "certificateNum", "affiliate", "leaderCount", "crewCount", "goodCount", "middleCount",
                        "badCount", "reportCount", "disciplineCount", "overtimeCount", "trainCount", "illegalCount", "totalScore", "result", ""},
                new int[]{4000, 8000, 4000, 6000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000},
                null, headStyle,
                new CellStyle[]{bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle, bodyStyle},
                mapList
        );
        poi.write2Response(response, "统计表_" + new Date().getTime());

    }


    private void processResults(List<AnnualAssess> annualAssessList) {
        for (AnnualAssess annualAssess : annualAssessList) {
            annualAssess.setTotalScore(100);
            annualAssess.setResult("合格");
            if (annualAssess.getLeaderCount() >= 6) {
                annualAssess.setTotalScore(annualAssess.getTotalScore() + 5);
            }
            if (annualAssess.getCrewCount() >= 8) {
                annualAssess.setTotalScore(annualAssess.getTotalScore() + 5);
            }
            annualAssess.setTotalScore(annualAssess.getTotalScore() - 5 * (annualAssess.getMiddleCount() + annualAssess.getReportCount() + annualAssess.getDisciplineCount() + annualAssess.getOvertimeCount()));
            if (annualAssess.getTotalScore() < 80 || annualAssess.getBadCount() > 0 || annualAssess.getTrainCount() > 0 || annualAssess.getIllegalCount() > 0) {
                annualAssess.setResult("不合格");
            }
        }
    }


}
